package com.ygy.controller;

import ch.qos.logback.core.util.FileUtil;
import com.ygy.utils.CustomException;
import com.ygy.utils.Result;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.undo.CannotUndoException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @className: FilesController
 * @author: Ye
 * @描述: TODD
 * 文件上传
 * @date: 2024/3/18 22:13 
 * @version: 1.0
 */

@RestController
public class FilesController {

    @Value("${server.ip}")
    private String serverIp;

    @Value("${server.port}")
    private String serverPort;

    @Value("${files.uploads.path}")
    private String filesUploadsPath;

    @PostMapping("/uploads")
    public Result uploads(@RequestParam MultipartFile file) throws IOException, CustomException {
        //拿到文件上传类型 image/pe
        System.out.println("文件上传");
         String contentType = file.getContentType();
        System.out.println(file.getContentType());
         List<String> listType = new ArrayList<>();
        //图片格式
        listType.add("image/png");
        listType.add("image/jpeg");
            listType.add("image/jpg");
        //视频格式
        listType.add("video/mp4");

        if (!listType.contains(contentType)){
            throw new CustomException("图片只允许“png. jpeg. jpg格式 视频只允许mp4格式");
        }

        InputStream inputStream = file.getInputStream();
        //生成文件名UUid
        String uuid = UUID.randomUUID().toString();
        //获取上传文件扩展名
        String fix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = uuid+fix;
        //生成完整路径
        String absolutePath = filesUploadsPath+fileName;

        File folder = new File(filesUploadsPath);
        //文件夹不存在就递归创建文件夹
        if (!folder.exists()){
            folder.mkdir();
        }
        int len = 0;
        FileOutputStream fileOutputStream = new FileOutputStream(absolutePath);
        while ((len=inputStream.read()) != -1 ){
            fileOutputStream.write(len);
        }
        fileOutputStream.close();
        inputStream.close();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("url","http://"+serverIp+":"+serverPort+"/views?fileName="+fileName);
        //返回上传名称
        map.put("alt",file.getOriginalFilename());
        return Result.success(map);
    }
    //文件下载
    @GetMapping("/views")
    public void viwews(@RequestParam String fileName, HttpServletResponse response) throws IOException {

        //对路径进行裁切
        final String[] split = fileName.split("/");
        final String name = split[split.length - 1];
        final File file = new File(filesUploadsPath + name);
        final Path filePath = Paths.get(filesUploadsPath, name);
        //设置输出流格式
        ServletOutputStream outputStream = response.getOutputStream();

        // 设置响应头，告诉浏览器这是一个文件下载操作
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));

        //任意类型的的二进制数据流
        response.setContentType("application/octet-stream");
        //读取文件字节流
        //outputStream.write(FileUtil.);
        // 读取文件字节流并写入输出流
        try (InputStream inputStream = Files.newInputStream(filePath)) {
            byte[] buffer = new byte[4096]; // 缓冲区大小可以根据需要调整
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        outputStream.flush();
        outputStream.close();

    }

}
